<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;">
      <div class="title">{{$t('achievements.title1')}}</div>
      <div class="menu-search">
        <div class="menu-title">
          <!-- APP渠道 -->
          <div class='searchItem'>
            <span>{{$t('ElectricChannel.AppChannel')}}</span>
            <el-select v-model='listQuery.channel'  size='small'>
                <el-option
                v-for='item in channelList'
                :key='item.channel'
                :label='item.org_name'
                :value='item.channel'>
                </el-option>
            </el-select>
          </div>
          <!-- 短信类型 -->
          <div class='searchItem'>
            <span>{{$t('sms.smsType')}}</span>
            <el-select v-model='listQuery.smsType'  size='small'>
                <el-option
                v-for='item in smsTypeList'
                :key='item.dictCode'
                :label='item.dictValue'
                :value='item.dictCode'>
                </el-option>
            </el-select>
          </div>
          <div class="menu-title-btn" style="margin-left: 20px;">
            <button type="button" @click="search">{{$t('btn.query')}}</button>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between;">
        <div class="title">{{$t('DailyStatistics.ListDetails')}}</div>
        <div>
          <el-button
            type="primary"
            size="small"
            @click="handleAddSmsTemplate"
          >{{$t('sms.addTemplate')}}</el-button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 5px;"
        border
        size="mini"
      >
        <el-table-column :label="$t('user.num')" header-align="center" align="center" width="60">
          <template slot-scope="scope">
            <span>{{scope.row.index}}</span>
          </template>
        </el-table-column>
        <!-- 短信类型 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="smsType"
          width="160"
          :label="$t('sms.smsType')"
        ></el-table-column>
        <!-- 短信说明 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="smsXplain"
          width="160"
          :label="$t('sms.smsXplain')"
        ></el-table-column>
        <!-- 短信内容 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="smsContent"
          :label="$t('sms.smsContent')"
        ></el-table-column>
        <!-- 短信状态 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="status"
          width="160"
          :label="$t('sms.status')"
        >
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.status" size="small" @change.native="changeRowStatus(scope.row)">
                <el-radio :label="1" size="mini">{{$t("AppVersion.enable")}}</el-radio>
                <el-radio :label="2" size="mini">{{$t("AppVersion.blockup")}}</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        
        <el-table-column align="center" header-align="center"  :label="$t('user.operation')" width="160">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="handleEdit(scope.row)" >{{$t('btn.edit')}}</el-button>
            <el-button size="small" type="text" @click="handleRemove(scope.row)">{{$t('sms.del')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[5, 10, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 还款类、预期类对话框 -->
    <el-dialog
      :title="textMap[dialogStatus2]"
      :visible.sync="dialogFormVisible2"
      :before-close="closeDialog"
    >
      <el-form
        :model="form" 
        :rules="rules" 
        ref="form" 
        label-position="top"
        label-width="100px"
        style="width:85%;margin-left:5%"
      >
        
          <!--禁用-->
          <template v-if="form.smsType==='验证类'||form.smsType==='放款成功类'">
            <el-form-item :label="$t('sms.smsType')" prop="smsType">
              <el-select v-model='form.smsType' disabled="" size='small'>
                <el-option
                v-for='item in formSmsTypeList'
                :key='item.dictCode'
                :label='item.dictValue'
                :value='item.dictValue'>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('sms.smsXplain')" prop="smsXplain">
              <el-input size="small" v-model="form.smsXplain" :placeholder="$t('sms.smsXplainRequired')"></el-input>
            </el-form-item>
          </template>
          <!---->
          <template v-else>
            <el-form-item :label="$t('sms.smsType')" prop="smsType">
              <el-select v-model='form.smsType'  size='small'>
                <el-option
                v-for='item in formSmsTypeList'
                :disabled="item.dictValue==='验证类'||item.dictValue==='放款成功类'"
                :key='item.dictCode'
                :label='item.dictValue'
                :value='item.dictValue'>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('sms.smsXplain')" prop="smsXplain">
              <el-input size="small" v-model="form.smsXplain" :placeholder="$t('sms.smsXplainRequired')"></el-input>
            </el-form-item>
            <el-form-item :label="dayText" prop="smsDays">
              <el-input size="small" v-model.number="form.smsDays" :placeholder="$t('sms.smsDaysRequired')"></el-input>
            </el-form-item>
          </template>
          
        
        <div style="position:relative;">
          <el-popover
            placement="right"
            :title="$t('sms.tooltipTitle')"
            width="250"
            trigger="click">
            <div>
              <ul style="list-style:none;padding:0;">
                <li>{{$t('sms.appName')}}: [Nama Aplikasi]</li>
                <li>{{$t('sms.verifyCode')}}: (kode Verifikasi)</li>
                <li>{{$t('sms.orderId')}}: [order number]</li>
                <li>{{$t('sms.deadDate')}}: [Repayment date]</li>
                <li>{{$t('sms.fromDueDate')}}: [From the due date]</li>
                <li>{{$t('sms.dueDay')}}: [Overdue days]</li>
              </ul>
              <!-- App名称：[Nama Aplikasi]<br/>验证码：(kode Verifikasi)<br/>订单号：[order number]<br/>到期日期：[Repayment date]<br/>距到期日：[From the due date]<br/>逾期天数：[Overdue days] -->
            </div>
            <a style="font-size:12px;color:#cc3333;position:absolute;top:10px;left:70px;" slot="reference">{{$t('sms.viewToolTip')}}</a>
          </el-popover>
          <el-form-item :label="$t('sms.smsContent')" prop="smsContent">
            <el-input type="textarea" v-model="form.smsContent" :autosize="{ minRows: 4, maxRows: 7}" :placeholder="$t('sms.smsContentRequired')"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button v-if="dialogStatus2=='create'" type="primary" :loading="submitBtnLoading" @click="submitCreateForm('form')">{{$t('btn.conserve')}}</el-button>
        <el-button v-else type="primary" @click="submitUpdateForm('form')">{{$t('btn.conserve')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getChannels } from 'api/customQuery/index';
import { smsTemplatePage, addSmsTemplate, changeSmsStatus, delSmsTemplate, getDict } from 'api/duanxin/index'
export default {
  data() {
    return {
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,
        page: 1,
        // 渠道
        channel: '',
        // 短信类型
        smsType: '',
        // 1.短信模板分页  2.短信群发配置
        smsTemplateType: '1'
        // 开始时间
        // crtTimeBegine: '',
        // 结束时间
        // crtTimeEnd: '',
        // 操作人
        // workUser: ''
      },
      // 渠道列表
      channelList: [],
      // 短信类型列表（有后台接口提供）
      smsTypeList: [{
        dictValue: '全部',
        dictCode: ''
      }],
      tableData: [],
      dialogStatus1: '',
      dialogStatus2: '',
      // 验证类、放款成功类编辑对话框显示状态
      dialogFormVisible1: false,
      // 还款类”、“逾期类对话框显示状态
      dialogFormVisible2: false,
      textMap: {
        update: this.$t('btn.edit'),
        create: this.$t('btn.create')
      },
      submitBtnLoading: false,
      // 短信类型数据源
      formSmsTypeList: [],
      // 还款类、逾期类表单数据
      form: {
        id: '',
        // 短信模板标题\短信说明
        smsXplain: '',
        // 短信模板类型
        smsType: '还款类提醒',
        // 逾期天数前/距离还款日前（几天）
        smsDays: '',
        // 短信内容
        smsContent: '',
        // 添加1 修改2
        addOrUpdate: '',
        // 1.短信模板添加模板  2.短信群发配置添加模板
        smsTemplateType: '1'
      },
      rules: {
        smsXplain: [{
          required: true,
          message: this.$t('sms.smsXplainRequired')
        }],
        smsType: [{
          required: true,
          message: this.$t('sms.smsTypeRequired')
        }],
        smsDays: [{
          required: true,
          message: this.$t('sms.smsDaysRequired')
        }, {
          type: 'number', message: this.$t('sms.smsDaysNumber')
        }],
        smsContent: [{
          required: true,
          message: this.$t('sms.smsContentRequired')
        }, {
          max: 1000,
          message: this.$t('sms.smsContentLess1000'),
          trigger: 'blur'
        }]
      }
    };
  },
  computed: {
    ...mapGetters(['elements', '']),
    dayText() {
      const smsType = this.form.smsType
      return smsType === '还款提醒类' ? this.$t('sms.fromDueDate') : this.$t('sms.dueDay')
    }
  },
  created() {
    // if (this.MessagePushPage.has(this.$route.path)) {
    //   this.listQuery = this.MessagePushPage.get(this.$route.path);
    // }
    // 获取渠道列表
    getChannels().then(res => {
      if (res.status === 200) {
        this.channelList = res.data
        this.listQuery.channel = res.data.length > 0 && res.data[0].channel

        this.getList();
      }
    })
    // 获取短信类型
    getDict().then(res => {
      if (res.status === 200) {
        const data = res.data
        data.forEach(item => {
          item.dictCode = item.dictValue
        })
        // console.log(data)
        this.smsTypeList = this.smsTypeList.concat(data)
        this.formSmsTypeList = res.data
      }
    })
  },
  methods: {
    // 添加短信模板
    handleAddSmsTemplate() {
      this.dialogStatus2 = 'create'
      this.dialogFormVisible2 = true
      this.form.smsType = '还款提醒类'
    },
    // 状态更改
    changeRowStatus(row) {
      this.$confirm(this.$t('sms.confirmTitle'), this.$t('group.cue2'), {
        confirmButtonText: this.$t('btn.confirm'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        changeSmsStatus({
          id: row.id,
          status: row.status
        }).then(res => {
          if (res.status === 200) {
            this.getList();
            this.$notify({
              title: this.$t('group.success'),
              message: this.$t('sms.success'),
              type: 'success',
              duration: 2000
            });
          }
        })
      }).catch(() => {
        row.status = row.status === 1 ? 2 : 1
        this.$message({
          type: 'info',
          message: this.$t('sms.cancel')
        })
      });
    },
    // 编辑
    handleEdit(row) {
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.form = Object.assign(this.form, row)
      // console.log(this.form)
    },
    // 删除
    handleRemove(row) {
      this.$confirm(this.$t('user.cue1'), this.$t('user.cue2'), {
        confirmButtonText: this.$t('btn.confirm'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        delSmsTemplate({ id: row.id }).then(res => {
          if (res.status === 200) {
            this.getList()
            this.$notify({
              title: this.$t('user.success'),
              message: this.$t('user.delsuccess'),
              type: 'success',
              duration: 2000
            });
          }
        })
      })
    },
    // 关闭
    closeDialog(done) {
      done()
      this.resetForm2()
      this.getList()
    },
    // 新增
    submitCreateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.addOrUpdate = 1
          this.form.channel = this.listQuery.channel
          this.save()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 更新
    submitUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.addOrUpdate = 2
          // this.form.channel = this.listQuery.channel
          this.save()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 保存
    save() {
      this.submitBtnLoading = true
      addSmsTemplate(this.form).then(res => {
        this.submitBtnLoading = false
        if (res.status === 200) {
          this.dialogFormVisible2 = false
          this.$notify({
            title: this.$t('groupType.success'),
            message: this.$t('groupType.crtsuccess'),
            type: 'success',
            duration: 2000
          });
          this.getList()
        }
      }).catch(() => {
        this.submitBtnLoading = false
      })
    },
    resetForm2() {
      this.$refs.form.resetFields();
      this.form = {
        id: '',
        // 短信模板标题\短信说明
        smsXplain: '',
        // 短信模板类型
        smsType: '还款类提醒',
        // 逾期天数前/距离还款日前（几天）
        smsDays: '',
        // 短信内容
        smsContent: '',
        // 添加1 修改2
        addOrUpdate: '',
        // 1.短信模板添加模板  2.短信群发配置添加模板
        smsTemplateType: '1'
      }
    },
    getList() {
      this.listLoading = true;
      // this.$store.dispatch("saveMessagePushPage", {
      //   path: this.$route.path,
      //   listQuery: this.listQuery
      // });
      const params = this.listQuery
      // params.smsType = params.smsType === '全部' ? '' : params.smsType
      smsTemplatePage(params).then(res => {
        this.listLoading = false
        if (res.status === 200) {
          const records = res.data.records
          const total = parseInt(res.data.total)
          records.forEach((item, index) => {
            item.index =
              index + (this.listQuery.page - 1) * this.listQuery.limit + 1;
          })
          this.tableData = records
          this.total = total
        }
      });
    },
    // 查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 200px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.el-form {
  label.el-form-item__label {
    line-height: 20px;
  }
}
</style>